import logging
from database import DatabaseManager
from web_crawler import WebCrawler
from monitor import TradeMonitor  # 修改为新的类名
from trade_simulator import TradeSimulator
from trade_executor import TradeExecutor
from selenium import webdriver  # 导入webdriver
from PyQt5.QtCore import QObject, pyqtSignal

logger = logging.getLogger(__name__)

class TradingSystem:

    # 定义数据变更信号
    trades_changed = pyqtSignal()  # 交易数据变更
    simulated_trades_changed = pyqtSignal()  # 跟单信息变更

    def __init__(self, db_path):
        #super().__init__()
        """初始化交易系统"""
        logger.info("初始化交易系统")
        self.db_path = db_path
        try:
            # 初始化WebDriver
            logger.info("开始初始化WebDriver...")
            self.driver = self.init_driver()
            logger.info("WebDriver初始化完成")

            # 初始化数据库管理器
            logger.info("开始初始化数据库管理器...")
            self.db_manager = DatabaseManager(db_path)  # 传入db_path
            logger.info("数据库管理器初始化完成")

            # 初始化爬虫
            logger.info("开始初始化爬虫...")
            self.crawler = WebCrawler(self.driver, self.db_manager)  # 需要driver
            logger.info("爬虫初始化完成")

            # 初始化交易模拟器
            logger.info("开始初始化交易模拟器...")
            self.simulator = TradeSimulator(self.db_manager)
            logger.info("交易模拟器初始化完成")

            # 初始化监控器
            logger.info("开始初始化监控器...")
            self.monitor = TradeMonitor(self.db_manager, self.crawler, self.simulator)  # 新代码, TradeSimulator(self.db_manager)
            logger.info("监控器初始化完成")

            # 初始化交易执行器
            logger.info("开始初始化交易执行器...")
            self.executor = TradeExecutor(self.db_manager)
            logger.info("交易执行器初始化完成")
            logger.info("交易系统初始化完成")
        except Exception as e:
            logger.error(f"交易系统初始化失败: {str(e)}")
            raise

    def init_driver(self):
        """初始化WebDriver"""
        try:
            options = webdriver.EdgeOptions()
            options.add_argument("--headless")  # 无头模式
            options.add_argument("--disable-gpu")
            options.add_argument("--no-sandbox")
            options.add_argument("--disable-dev-shm-usage")
            driver = webdriver.Edge(options=options)
            logger.info("WebDriver初始化完成")
            return driver
        except Exception as e:
            logger.error(f"WebDriver初始化失败: {str(e)}")
            return None

#    def get_db_manager(self):
#        """获取数据库管理器"""
#        return self.db_manager
    
#    def get_evaluator(self):
#        """获取绩效评估器"""
#        return self.evaluator
    
#    def get_monitor(self):
#        """获取监控器"""
#        return self.monitor
    
#    def get_executor(self):
#        """获取交易执行器"""
#        return self.executor
    
#    def get_crawler(self):
#        """获取网页爬虫"""
#        return self.crawler